﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Security.Cryptography;
using System.Data;
using System.Configuration;
using System.Net;
using Portal.Core;


namespace Portal.Admin.Screen.Render
{
    public class SecurityServices
    {
        #region Static Fields
            private static ImageVerification v = new ImageVerification();
            static int imgWidth = 220, imgHeight = 30;
        #endregion

        #region EncryptionPassword
            private static int randomNumber()
            {
                string strSource = "1234567890";
                Random r = new Random();
                int Index = Convert.ToInt32(r.Next(3, strSource.Length - 1));
                return Index;
            }

            public static string GetMD5(string chuoi)
            {
                string str_md5 = "";
                byte[] mang = System.Text.Encoding.UTF8.GetBytes(chuoi);
                MD5CryptoServiceProvider my_md5 = new MD5CryptoServiceProvider();
                mang = my_md5.ComputeHash(mang);
                foreach (byte b in mang)
                {
                    str_md5 += b.ToString("X2");
                }
                return str_md5;
            }

            public static string EncryptionString(string chuoi)
            {
                int ilength = randomNumber();
                char[] stemp = chuoi.ToCharArray();

                string strResult = "";
                for (int j = 0; j < stemp.Length; j++)
                {
                    System.Threading.Thread.Sleep(30);
                    strResult = strResult + stemp[j].ToString() + v.SetRandomPassword(ilength);
                }
                return ilength.ToString() + strResult;
            }
        #endregion

        #region Session And Cookie 
        
        //public static UserToken uUserToken = new eDManWs.UserToken();

        //[AjaxPro.AjaxMethod]
        //public string CheckLogin(string username, string password)
        //{
        //    try
        //    {
        //        UserToken userToken = null;
                
        //        string warningText = string.Empty;

        //        /*
        //        if (!CmsBLL.PingHost())
        //        {
        //            warningText = "ERROR: Dịch vụ của chương trình hiện không hoạt động, vui lòng liên hệ quản trị hệ thống.";
        //            return CmsBLL.ConnectError(warningText);
        //        }

        //        CalendarWs.Service _sysws = new CalendarWs.Service();
        //        _sysws.Url = CommonBLL.UrlCalendarServices;
        //        if (!_sysws.IsDBOnline())
        //        {
        //            warningText = "ERROR: Không thể kết nối tới máy chủ Database, vui lòng liên hệ quản trị hệ thống.";
        //            return CmsBLL.ConnectError(warningText);
        //        }
        //        */

        //        userToken = CheckAuthenticate(eD.Utilities.EncDec.Encrypt(username, "cmc"), eD.Utilities.EncDec.Encrypt(password, "cmc"));
        //        if (userToken != null)
        //            return "1";
        //        else
        //            return "0";
        //    }
        //    catch (Exception ex)
        //    {
        //        return "0";
        //    }
        //}

        //[AjaxPro.AjaxMethod]
        //public void LoginSuccess(string username)
        //{
        //    SetCurrentUser(username);
        //}

        //[AjaxPro.AjaxMethod]
        //public void Logout()
        //{
        //    HttpContext.Current.Session.Abandon();
        //}

        //public UserToken CheckAuthenticate(string userName, string password)
        //{
        //    //string[] UserInfo = null;
        //    try
        //    {
        //        UserToken userToken = null;
        //        eDManWs.WsInParamCls oWsInParamCls = WsBLL.CreateWsInParamCls(eDManWs.eDCommand.Authenticate);

        //        oWsInParamCls.UserToken = new eDManWs.UserToken();
        //        oWsInParamCls.UserToken.LoginName = userName;//eD.Utilities.EncDec.Encrypt(userName, "cmc");
        //        oWsInParamCls.UserToken.Password = password;//.Utilities.EncDec.Encrypt(password, "cmc");

        //        eDManWs.WsReturnParamCls oWsReturnParamCls = WsBLL.CreateWs().ProcessCommand(oWsInParamCls);
        //        if (!string.IsNullOrEmpty(oWsReturnParamCls.XmlResult))
        //            userToken = UserToken.Parse(oWsReturnParamCls.XmlResult);

        //        if (userToken != null && userToken.GroupID != "")
        //        {
        //            SetUserInfo(userToken);
        //            SetCurrentYear(System.DateTime.Now.Year.ToString());
        //            return userToken;
        //        }
        //        else
        //            return null;
               
        //    }
        //    catch (Exception ex)
        //    {
        //        return null;
        //    }
        //}

         [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static string CreateCaptcha()
        {
            StringBuilder Html = new StringBuilder();
            try
            {
                v.ProcessRequest(imgWidth, imgHeight);
                string pathImageVerification = (string)System.Configuration.ConfigurationManager.AppSettings["CapchaImageRoot"];
                Html.Append(
                            "<td>" +
                            "   <label class=\"ftl\" for=\"captcha\">Mã xác nhận</label>\n" +                            
                            "</td>" +
                            "<td>" +
                            "   <input type=\"text\" name=\"captcha\" id=\"captcha\" onkeypress=\"javascript:onKeyupInputText(event, this, 'Yêu cầu nhập vào mã xác thực');\">\n" +
                            "   <img class=\"ftr\" id=\"ImgCaptcha\" src=\"" + pathImageVerification + HttpContext.Current.Session["fileNameCodeImageVerifier"].ToString() + "\" />\n" +
                            "   <input type=\"hidden\" name=\"dhtn\" id=\"dhtn\" value=\"" + v.checkCodeVerifier() + "\">\n" +
                            "</td>");
                HttpContext.Current.Session.Remove("fileNameCodeImageVerifier");
                return Html.ToString();
            }
            catch (Exception ex) { ex.Message.ToString(); }
            {
                return "";
            }
        }


         [AjaxPro.AjaxMethod()]
         public static AjaxOut CreateCaptchaNew()
         {
             AjaxOut OAjaxOut = new AjaxOut();
             StringBuilder Html = new StringBuilder();
             try
             {
                 v.ProcessRequest(imgWidth, imgHeight);
                 string pathImageVerification = (string)System.Configuration.ConfigurationManager.AppSettings["CapchaImageRoot"];
                 Html.Append(
                             "<td>" +
                             "   <label class=\"ftl\" for=\"captcha\">Mã xác nhận</label>\n" +
                             "</td>" +
                             "<td>" +
                             "   <input type=\"text\" name=\"captcha\" id=\"captcha\" onkeypress=\"javascript:onKeyupInputText(event, this, 'Yêu cầu nhập vào mã xác thực');\">\n" +
                             "   <img class=\"ftr\" id=\"ImgCaptcha\" src=\"" + pathImageVerification + HttpContext.Current.Session["fileNameCodeImageVerifier"].ToString() + "\" />\n" +
                             "   <input type=\"hidden\" name=\"dhtn\" id=\"dhtn\" value=\"" + v.checkCodeVerifier() + "\">\n" +
                             "</td>");
                 HttpContext.Current.Session.Remove("fileNameCodeImageVerifier");
                 OAjaxOut.HtmlContent = Html.ToString();
                 
             }
             catch (Exception ex) { ex.Message.ToString(); }
             {
                 //return "";
             }
             return OAjaxOut;
         }

        //[AjaxPro.AjaxMethod]
        //public static bool IsCaptchaAvailable()
        //{
        //    bool value = false;
        //    try
        //    {
        //        if (CommonBLL.CaptchaAvailable.Equals(1))
        //            value = true;
        //    }
        //    catch (Exception)
        //    { }

        //    return value;
        //}

        //public static void SetUserInfo(UserToken userToken)
        //{
        //    HttpContext.Current.Session["usertoken"] = UserToken.GetXml(userToken);
        //}

        //public static UserToken GetUserInfo()
        //{
        //    return UserToken.Parse(HttpContext.Current.Session["usertoken"].ToString());
        //}

        //[AjaxPro.AjaxMethod]
        //public static void SetCurrentYear(string year)
        //{
        //    HttpContext.Current.Session["crryear"] = year;
        //    UserToken usertoken = GetUserInfo();
        //    usertoken.CurrentDbYear = int.Parse(year);
        //    HttpContext.Current.Session["usertoken"] = UserToken.GetXml(usertoken);
        //}

        public static string GetCurrentYear()
        {
            return HttpContext.Current.Session["crryear"].ToString();
        }

        [AjaxPro.AjaxMethod]
        public static void SetDocumentTypeID(string DocumentTypeID)
        {
            HttpContext.Current.Session["doctypeid"] = DocumentTypeID;
        }

        public static string GetDocumentTypeID()
        {
            return HttpContext.Current.Session["doctypeid"].ToString();
        }

        #endregion        
    }
}
